//
//  RCDUtilsMacro.h
//  chengshiquan
//
//  Created by 任辰东 on 17/3/6.
//  Copyright © 2017年 任辰东. All rights reserved.
//

#ifndef RCDUtilsMacro_h
#define RCDUtilsMacro_h

#pragma mark - log

#ifdef DEBUG
#define DString [NSString stringWithFormat:@"%s", __FILE__].lastPathComponent
#define DLog(...) printf("\n************\n%s 第%d行: %s\n************\n", [DString UTF8String] ,__LINE__, [[NSString stringWithFormat:__VA_ARGS__] UTF8String]);
#else

#define DLog(...)
#endif

#pragma mark - normal

#define kAppDelegate ((AppDelegate *)[UIApplication sharedApplication].delegate)
#define kKeyWindow ((UIWindow *)[UIApplication sharedApplication].keyWindow)
#define UIFontSize(fontSize) [UIFont systemFontOfSize:FitFontSize(fontSize)]
#define UIBoldFontSize(fontSize) [UIFont boldSystemFontOfSize:FitFontSize(fontSize)]
#define UIImageWithName(imageName) [UIImage imageNamed:imageName]
#define kCurrentBundleVersion ((NSString *)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"])
#define kBundleId [[NSBundle mainBundle] bundleIdentifier]

#pragma mark - filepath

//Library/Caches 文件路径
#define FilePath ([[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil])
//获取temp
#define kPathTemp NSTemporaryDirectory()
//获取沙盒 Document
#define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
//获取沙盒 Cache
#define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

#pragma mark - device

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPOD ([[[UIDevice currentDevice] model] isEqualToString:@"iPod touch"])

#pragma mark - screen

#define iPhone4Or4S ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone5Or5s ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone6Or7Or8OrSE2 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhoneXR ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhoneXsMax ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) : NO)
#pragma mark - system

#define iOS14OrLater ([[[UIDevice currentDevice] systemVersion]doubleValue]>=14.0f)
#define iOS13OrLater ([[[UIDevice currentDevice] systemVersion]doubleValue]>=13.0f)

#pragma mark - color

#define UIColorFromHexWithAlpha(hexValue,a) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:a]
#define UIColorFromHex(hexValue)            UIColorFromHexWithAlpha(hexValue,1.0)
#define UIColorFromRGBA(r,g,b,a)            [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
#define UIColorFromRGB(r,g,b)               UIColorFromRGBA(r,g,b,1.0)

#pragma mark - indexPath

#define INDEX_PATH(a,b) [NSIndexPath indexPathWithIndexes:(NSUInteger[]){a,b} length:2]

#pragma mark - transforms

#define DEGREES_TO_RADIANS(degrees) degrees * M_PI / 180

#pragma mark - other

#define kOnePixel (1.0f / [UIScreen mainScreen].scale)
#define WeakSelf @weakify(self);
#define StrongSelf @strongify(self);

/*
 弱引用/强引用  可配对引用在外面用RCDWeakSelf(self)，block用RCDStrongSelf(self)
 也可以单独引用在外面用RCDWeakSelf(self) block里面用weakself
 */
#define RCDWeakSelf(type)  __weak typeof(type) weak##type = type;
#define RCDStrongSelf(type)  __strong typeof(type) type = weak##type;

#pragma mark - size

#define kScreenScale ([UIScreen mainScreen].scale)
#define kScreenWidth ([UIScreen mainScreen].bounds.size.width)
#define kScreenHeight ([UIScreen mainScreen].bounds.size.height)
#define kScreen_Ratio_W ([UIScreen mainScreen].bounds.size.width/375)
#define kScreen_Ratio_H ([UIScreen mainScreen].bounds.size.height/667)

#define kNavitionBarHeight (kKeyWindow.windowScene.statusBarManager.statusBarFrame.size.height+44)
#define KStatusBarHeight (kKeyWindow.windowScene.statusBarManager.statusBarFrame.size.height)
#define kBottomOffset (kKeyWindow.windowScene.statusBarManager.statusBarFrame.size.height > 20 ? (-34) : 0)
#define kSortListWidth (kScreenWidth / 4.4)
#define kSortGoodsListWidth (kScreenWidth - kSortListWidth)
#define kTabarHeight (kKeyWindow.windowScene.statusBarManager.statusBarFrame.size.height>20? 83 : 49)

// 安全区域（不包含状态栏）
#define SAFE_TOP   (kKeyWindow.windowScene.statusBarManager.statusBarFrame.size.height>20? 24.0f : 0.0f)

#define kRMBPrefix @"￥"

#pragma mark - font

static float const kNavBarTitleFont = 20;

static float const kFontA1 = 12;
static float const kFontA2 = 12;
static float const kFontA3 = 13;
static float const kFontA4 = 14;

static float const kFontB1 = 15;
static float const kFontB2 = 16;
static float const kFontB3 = 17;
static float const kFontB4 = 18;
static float const kFontB5 = 19;

static float const kFontC1 = 20;
static float const kFontC3 = 21;
static float const kFontC2 = 22;

static float const kPaddingTop = 15;
static float const kPaddingLeft = 15;
static float const kPaddingRight = -15;
static float const kPaddingBottom = -15;

#pragma mark - color

static int const kColorNavBarTitle = 0xffffff;//黑色
//主色
static int const kColorMain = 0xFF3300;
//配色
static int const kColorMatch = 0xCCCCCC;
//点缀色
static int const kColorEmbellish = 0x00CCFF;

//背景色
static int const kColorBG = 0xF5F5F5;
static int const kColorLine = 0xE8E8E8;

//提示
static int const kColorTipsError = 0xff6c6c;
static int const kColorTipsSuccess = 0x31c27c;

//标题颜色
static int const kColorBlack = 0x000000;//黑色
static int const kColorWhite = 0xffffff;//白色
static int const kColorTitle = 0x333333;
static int const kColorSubTitle = 0x666666;
static int const kColorPlaceholder = 0x999999;

#pragma mark - static method

static inline BOOL IsEmpty(id thing) {
    return thing == nil || [thing isEqual:[NSNull null]]
    || ([thing respondsToSelector:@selector(length)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [(NSArray *)thing count] == 0);
}

static inline id objectForKey(NSDictionary *dict, NSString *key)
{
    if (!([dict isKindOfClass:[NSDictionary class]] || [dict isKindOfClass:[NSMutableDictionary class]])) {
        return nil;
    }
    if (dict.count == 0 || !dict)
    {
        return nil;
    }
    if (!key) {
        return nil;
    }
    id object = [dict objectForKey:key];
    return [object isEqual:[NSNull null]] ? nil : object;
}

static inline id objectAtArrayIndex(NSArray *array, NSUInteger index)
{
    if (!([array isKindOfClass:[NSArray class]] || [array isKindOfClass:[NSMutableArray class]])) {
        return nil;
    }
    if (array && array.count > index) {
        return array[index];
    } else {
        return nil;
    }
}

/**
 *  把一个数据模型里的属性根据属性名保存到字典里，空值将会忽略掉
 *
 *  @param model 模型类
 *
 *  @return 不包含空值的（一维）可变字典
 */
static inline NSMutableDictionary* GetDictFromModel(id model)
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    unsigned int outCount;
    Ivar * ivars = class_copyIvarList([model class], &outCount);
    for (int i = 0; i < outCount; i ++) {
        Ivar ivar = ivars[i];
        NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        if (!IsEmpty([model valueForKey:key]) && !IsEmpty(key)) {
            [dict setObject:[model valueForKey:key] forKey:key];
        }
    }
    return dict;
}

static inline void onMainThreadAsync(void (^block)(void))
{
    if ([NSThread isMainThread]) block();
    else dispatch_async(dispatch_get_main_queue(), block);
}

//字体适配方法，iphone6plus为基准
static inline CGFloat FitFontSize(CGFloat fontSize)
{
//    if (kScreenWidth == 414) {
//        return fontSize;
//    }else if(kScreenWidth == 375){
//        return fontSize * (kScreenWidth/(375 + 20)); //+20修正系数
//    }else if(kScreenWidth > 414){
//        return fontSize * (kScreenWidth/(kScreenWidth -414)/2 + 414); //横屏或者更大尺寸
//    } else {
//        return fontSize * (kScreenWidth/(320 + 40));//-40 修正系数
//    }
    return fontSize;
}

#endif /* RCDUtilsMacro_h */
